import 'dart:io';
import 'package:flutter/material.dart';
import 'package:cached_network_image/cached_network_image.dart';

class CircleAvatarButton extends StatelessWidget {
  final String? imageUrl; // 网络图片URL（可选）
  final ImageProvider? defaultImage; // 本地默认图片（可选）
  final double size; // 直径
  final VoidCallback onPressed; // 点击回调
  final Color borderColor; // 边框颜色
  final double borderWidth; // 边框宽度

  const CircleAvatarButton({
    super.key,
    this.imageUrl,
    this.defaultImage,
    this.size = 60,
    required this.onPressed,
    this.borderColor = Colors.transparent,
    this.borderWidth = 0,
  }) : assert(
         imageUrl != null || defaultImage != null,
         '必须提供 imageUrl 或 defaultImage',
       );

  @override
  Widget build(BuildContext context) {
    // 外层用 SizedBox 锁定宽高，避免被父布局拉伸
    return SizedBox(
      width: size,
      height: size,
      child: Material(
        color: Colors.transparent,
        shape: CircleBorder(
          side: BorderSide(color: borderColor, width: borderWidth),
        ),
        child: InkWell(
          customBorder: const CircleBorder(),
          onTap: onPressed,
          child: _buildAvatarBody(),
        ),
      ),
    );
  }

  Widget _buildAvatarBody() {
    final placeholderDecoration = BoxDecoration(
      shape: BoxShape.circle,
      color: Colors.grey[300],
    );

    if (imageUrl != null && imageUrl!.isNotEmpty) {
      if (imageUrl!.startsWith('http')) {
        return CachedNetworkImage(
          key: ValueKey('avatar_$imageUrl'), // 为每个头像添加唯一 key
          imageUrl: imageUrl!,
          cacheKey: imageUrl, // 使用完整 URL 作为 cacheKey
          memCacheWidth: (size * 2).toInt(),
          memCacheHeight: (size * 2).toInt(),
          maxWidthDiskCache: (size * 2).toInt(),
          maxHeightDiskCache: (size * 2).toInt(),
          fadeInDuration: Duration.zero,
          // 当图片成功加载时，使用装饰来绘制圆形并 cover
          imageBuilder: (context, imageProvider) {
            return Container(
              // SizedBox 的约束会传到这里，因此无需再设置 width/height
              decoration: BoxDecoration(
                shape: BoxShape.circle,
                image: DecorationImage(image: imageProvider, fit: BoxFit.cover),
              ),
            );
          },
          // 加载中与失败时都显示相同的占位（不显示错误图标）
          placeholder: (context, url) =>
              Container(decoration: placeholderDecoration),
          errorWidget: (context, url, error) =>
              Container(decoration: placeholderDecoration),
        );
      } else {
        return Container(
          decoration: BoxDecoration(
            shape: BoxShape.circle,
            image: DecorationImage(
              image: FileImage(File(imageUrl!)),
              fit: BoxFit.cover,
            ),
          ),
        );
      }
    }

    // 本地默认图片（ImageProvider）也用 DecorationImage，避免拉伸
    if (defaultImage != null) {
      return Container(
        decoration: BoxDecoration(
          shape: BoxShape.circle,
          image: DecorationImage(image: defaultImage!, fit: BoxFit.cover),
        ),
      );
    }

    // 理论上不会到这里（assert 已保证），但仍保底
    return Container(decoration: placeholderDecoration);
  }
}
